"""
conversation_manager_dialog.py
对话管理窗口的实现
"""

from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton, 
                            QListWidget, QListWidgetItem, QLabel, QWidget,
                            QMessageBox, QInputDialog, QLineEdit)
from PyQt6.QtCore import Qt, pyqtSignal
from styles import SETTINGS_BUTTON_STYLE, LABEL_STYLE, INPUT_STYLE, BLUE_BUTTON_STYLE

class ConversationManagerDialog(QDialog):
    """对话管理窗口"""
    conversation_updated = pyqtSignal()  # 当对话列表更新时发出
    
    def __init__(self, conversation_manager, current_model, parent=None):
        super().__init__(parent)
        self.conversation_manager = conversation_manager
        self.current_model = current_model
        self.setWindowTitle(f"对话管理 - {current_model}")
        self.setFixedSize(300, 400)
        self.setup_ui()
        self.temp_conversations = {}  # 临时存储对话数据
        self.temp_names = {}  # 临时存储对话名称
        self.next_id = 1  # 临时存储下一个ID
        self.load_conversations()  # 从conversation_manager加载当前配置到临时存储
        self.changes_made = False  # 用于跟踪是否有未保存的更改
        
        # 修改对话列表为多选模式
        self.conversation_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        
        # 对话列表
        self.conversation_list = QListWidget()
        self.conversation_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        self.conversation_list.setDragDropMode(QListWidget.DragDropMode.InternalMove)
        self.conversation_list.model().rowsMoved.connect(self.on_rows_moved)
        self.conversation_list.itemDoubleClicked.connect(self.select_conversation)
        self.conversation_list.setStyleSheet("""
            QListWidget {
                border: 1px solid #cccccc;
                border-radius: 4px;
                background-color: white;
            }
            QListWidget::item {
                padding: 5px;
                border-bottom: 1px solid #eeeeee;
            }
            QListWidget::item:selected {
                background-color: #007bff;
                color: white;
            }
            QListWidget::item:hover {
                background-color: #f5f5f5;
            }
            QListWidget::item:selected:hover {
                background-color: #0056b3;
                color: white;
            }
            QListWidget::item:selected:active {
                background-color: #004085;
                color: white;
            }
        """)
        layout.addWidget(self.conversation_list)
        
        # 添加标签显示对话数量
        self.count_label = QLabel()
        self.update_count_label()  # 移到这里，确保 conversation_list 已经创建
        layout.addWidget(self.count_label)

        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(5)
        
        # 添加按钮
        self.add_button = QPushButton("添加对话")
        self.add_button.setStyleSheet(SETTINGS_BUTTON_STYLE)
        self.add_button.clicked.connect(self.add_conversation)
        button_layout.addWidget(self.add_button)

        # 批量删除按钮
        self.delete_selected_button = QPushButton("删除所选")
        self.delete_selected_button.setStyleSheet(SETTINGS_BUTTON_STYLE)
        self.delete_selected_button.clicked.connect(self.delete_selected_conversations)
        button_layout.addWidget(self.delete_selected_button)

        # 编辑按钮
        self.edit_button = QPushButton("编辑对话")
        self.edit_button.setStyleSheet(SETTINGS_BUTTON_STYLE)
        self.edit_button.clicked.connect(self.handle_edit_save)
        button_layout.addWidget(self.edit_button)

        # 保存按钮
        self.save_button = QPushButton("保存更改")
        self.save_button.setStyleSheet(SETTINGS_BUTTON_STYLE)
        self.save_button.clicked.connect(self.save_changes)
        button_layout.addWidget(self.save_button)

        layout.addLayout(button_layout)

    def load_conversations(self):
        """加载对话列表到临时存储"""
        self.conversation_list.clear()
        
        # 从conversation_manager加载数据到临时存储
        if self.current_model in self.conversation_manager.chat_history:
            self.temp_conversations = self.conversation_manager.chat_history[self.current_model].copy()
            self.temp_names = self.conversation_manager.conversation_names[self.current_model].copy()
            self.next_id = self.conversation_manager.next_conversation_id.get(self.current_model, 1)
        else:
            self.temp_conversations = {}
            self.temp_names = {}
            self.next_id = 1
            
        # 更新列表显示
        for conv_id, name in self.temp_names.items():
            item = QListWidgetItem(name)
            item.setData(Qt.ItemDataRole.UserRole, conv_id)
            self.conversation_list.addItem(item)
            
        # 选中第一个对话
        if self.conversation_list.count() > 0:
            self.conversation_list.setCurrentRow(0)
            
        # 更新对话数量显示
        self.update_count_label()

    def add_conversation(self):
        """添加新对话"""
        # 在临时存储中添加新对话
        conv_id = self.next_id
        self.next_id += 1
        self.temp_conversations[conv_id] = []
        self.temp_names[conv_id] = "新对话"  # 使用默认名称
        
        # 更新显示（插入到最前面）
        item = QListWidgetItem("新对话")
        item.setData(Qt.ItemDataRole.UserRole, conv_id)
        self.conversation_list.insertItem(0, item)  # 插入到第一个位置
        self.conversation_list.setCurrentRow(0)  # 选中新添加的对话
        
        self.changes_made = True
        
        # 保存更改
        self.save_changes()
        
        # 设置为当前对话并更新主界面
        self.conversation_manager.set_current_conversation(self.current_model, conv_id)
        self.conversation_updated.emit()
        
        # 关闭窗口
        self.accept()

    def handle_edit_save(self):
        """处理编辑/保存按钮点击"""
        current_item = self.conversation_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "错误", "请先选择一个对话！")
            return

        # 进入编辑状态
        new_name, ok = QInputDialog.getText(
            self,
            "重命名对话",
            "请输入新的对话名称：",
            text=current_item.text()
        )
        
        if ok and new_name.strip():
            # 更新临时存储中的对话名称
            conv_id = current_item.data(Qt.ItemDataRole.UserRole)
            self.temp_names[conv_id] = new_name.strip()
            
            # 更新显示
            current_item.setText(new_name.strip())
            self.changes_made = True
            
            # 保存更改
            self.save_changes()
            
            # 设置为当前对话并更新主界面
            self.conversation_manager.set_current_conversation(self.current_model, conv_id)
            self.conversation_updated.emit()
            
            # 关闭窗口
            self.accept()

    def delete_selected_conversations(self):
        """删除选中的对话"""
        selected_items = self.conversation_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "错误", "请先选择要删除的对话！")
            return
            
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除选中的 {len(selected_items)} 个对话吗？此操作不可恢复。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            for item in selected_items:
                conv_id = item.data(Qt.ItemDataRole.UserRole)
                del self.temp_conversations[conv_id]
                del self.temp_names[conv_id]
                self.conversation_list.takeItem(self.conversation_list.row(item))
                
            self.changes_made = True  # 标记有未保存的更改
            self.update_count_label()  # 更新对话数量显示
            
            # 如果删除后没有对话了，创建新对话
            if self.conversation_list.count() == 0:
                self.add_conversation()
            else:
                # 选中第一个对话
                self.conversation_list.setCurrentRow(0)

    def select_conversation(self, item):
        """双击选中对话并更新主界面"""
        conv_id = item.data(Qt.ItemDataRole.UserRole)
        # 设置为当前对话并更新主界面
        self.conversation_manager.set_current_conversation(self.current_model, conv_id)
        self.conversation_updated.emit()
        self.accept()  # 关闭对话管理窗口

    def save_changes(self):
        """保存所有更改"""
        # 更新conversation_manager中的数据
        if self.current_model not in self.conversation_manager.chat_history:
            self.conversation_manager.chat_history[self.current_model] = {}
            self.conversation_manager.conversation_names[self.current_model] = {}
            self.conversation_manager.next_conversation_id[self.current_model] = 1

        self.conversation_manager.chat_history[self.current_model] = self.temp_conversations.copy()
        self.conversation_manager.conversation_names[self.current_model] = self.temp_names.copy()
        self.conversation_manager.next_conversation_id[self.current_model] = self.next_id
        
        # 保存到文件
        self.conversation_manager.save_chat_history()
        self.changes_made = False
        
        # 更新对话数量显示
        self.update_count_label()
        
        # 发送更新信号
        self.conversation_updated.emit()
        
        # 显示保存成功提示
        QMessageBox.information(
            self,
            "保存成功",
            f"已保存 {self.conversation_list.count()} 个对话。",
            QMessageBox.StandardButton.Ok
        )

    def on_rows_moved(self, parent, start, end, destination, row):
        """处理拖拽完成事件"""
        self.changes_made = True
        
        # 更新临时存储中的顺序
        new_temp_conversations = {}
        new_temp_names = {}
        for i in range(self.conversation_list.count()):
            item = self.conversation_list.item(i)
            conv_id = item.data(Qt.ItemDataRole.UserRole)
            new_temp_conversations[conv_id] = self.temp_conversations[conv_id]
            new_temp_names[conv_id] = self.temp_names[conv_id]
        
        self.temp_conversations = new_temp_conversations
        self.temp_names = new_temp_names
        
        # 临时更新主界面显示
        self.update_main_window()

    def update_count_label(self):
        """更新对话数量标签"""
        current_count = self.conversation_list.count()
        self.count_label.setText(f"当前对话数量: {current_count}/{self.conversation_manager.MAX_CONVERSATIONS}")
        self.count_label.setStyleSheet(
            "color: #ff0000;" if current_count >= self.conversation_manager.MAX_CONVERSATIONS else "color: #000000;"
        )

    def closeEvent(self, event):
        """关闭窗口时检查是否有未保存的更改"""
        if self.changes_made:
            reply = QMessageBox.question(
                self, '未保存的更改',
                '您有未保存的更改，是否要保存？',
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel,
                QMessageBox.StandardButton.Cancel
            )

            if reply == QMessageBox.StandardButton.Yes:
                self.save_changes()
                event.accept()
            elif reply == QMessageBox.StandardButton.No:
                # 重新加载原始数据，放弃所有更改
                if self.current_model in self.conversation_manager.chat_history:
                    self.temp_conversations = self.conversation_manager.chat_history[self.current_model].copy()
                    self.temp_names = self.conversation_manager.conversation_names[self.current_model].copy()
                    self.next_id = self.conversation_manager.next_conversation_id.get(self.current_model, 1)
                # 发送更新信号，刷新主界面
                self.conversation_updated.emit()
                event.accept()
            else:  # Cancel
                event.ignore()
        else:
            event.accept() 